<template>
  <ContentWrap>
		<!-- //定时任务配置 -->
	  <el-form
	    class="-mb-15px"
	    :model="queryParamsConfig"
	    ref="queryFormRefConfig"
	    :inline="true"
	    label-width="68px"
	  >
    <el-form-item label="" prop="type">
      <!-- 将所有内容放在一个flex布局中，实现一行展示 -->
      <div style="display: flex; align-items: center;">
        <span style="width: 150px;">每天</span>
        <el-time-select
          v-model="scheduledTaskConfigurationVO.publishedDayStart"
          :max-time="scheduledTaskConfigurationVO.publishedDayEnd"
          class="mr-1"
          placeholder="开始时间"
          start="08:30"
          step="00:15"
          end="22:30"
        />
        <span>-</span>
        <el-time-select
          v-model="scheduledTaskConfigurationVO.publishedDayEnd"
          :min-time="scheduledTaskConfigurationVO.publishedDayStart"
          placeholder="结束时间"
          start="08:30"
          step="00:15"
          end="22:30"
        />
        <span style="width: 150px;">间隔</span> <el-input v-model="scheduledTaskConfigurationVO.publishedIntervalStart" placeholder="40-350" @change="validateInterval($event, 'publishedIntervalStart')" />
        <span style="width: 1000px;">分钟随机生成一条发布数据</span>
      </div>
    </el-form-item><br/>
	    
    <el-form-item label="" prop="type">
      <!-- 将所有内容放在一个flex布局中，实现一行展示 -->
      <div style="display: flex; align-items: center; flex-wrap: nowrap; gap: 8px;">
        <span style="width: 150px;">每天</span>
        <el-time-select
          v-model="scheduledTaskConfigurationVO.dealDayStart"
          :max-time="scheduledTaskConfigurationVO.dealDayEnd"
          class="mr-1"
          placeholder="开始时间"
          start="08:30"
          step="00:15"
          end="22:30"
        />
        <span>-</span>
        <el-time-select
          v-model="scheduledTaskConfigurationVO.dealDayEnd"
          :min-time="scheduledTaskConfigurationVO.dealDayStart"
          placeholder="结束时间"
          start="08:30"
          step="00:15"
          end="22:30"
        />
        <span style="width: 150px;">间隔</span> <el-input v-model="scheduledTaskConfigurationVO.dealIntervalStart" placeholder="40-350" @change="validateInterval($event, 'dealIntervalStart')"/>
        <span style="width: 1000px;">分钟随机生成一条成交数据</span>
      </div>
    </el-form-item>
	    <el-form-item>
	      <el-button @click="updateScheduledTaskConfiguration"><Icon icon="ep:aim" class="mr-5px" /> 立即生效</el-button>
	    
	    </el-form-item>
	  </el-form>
  </ContentWrap>
  <ContentWrap>
	  
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="类型" prop="type">
              <el-select
                v-model="queryParams.type"
                placeholder="请选择类型"
                clearable
                class="!w-240px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.TASK_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
		</el-form-item>
      <el-form-item label="推送时间" prop="pushTime">
        <el-date-picker
          v-model="queryParams.pushTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
    
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="类型" align="center" prop="type" />
	  <el-table-column
	    label="推送时间"
	    align="center"
	    prop="pushTime"
	    :formatter="dateFormatter"
	    width="180px"
	  />
      <el-table-column label="内容" align="center" prop="content" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ScheduledTaskForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ScheduledTaskApi, ScheduledTaskVO } from '@/api/dd/scheduledtask'
import ScheduledTaskForm from './ScheduledTaskForm.vue'
//定时任务配置接口
import { ScheduledTaskConfigurationApi, ScheduledTaskConfigurationVO } from '@/api/dd/scheduledtaskconfiguration'

/** 定时任务数据 列表 */
defineOptions({ name: 'ScheduledTask' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ScheduledTaskVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  type: undefined,
  pushTime: [],
  content: undefined,
  state: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

//定时任务配置
const queryParamsConfig = reactive({
  pageNo: 1,
  pageSize: 10,
  type: undefined,
  pushTime: [],
  content: undefined,
  state: undefined,
  createTime: [],
})

const scheduledTaskConfigurationVO = reactive({
  publishedDayStart: '', // 发布数据每天开始时间
  publishedDayEnd: '', // 发布数据每天结束时间
  publishedIntervalStart: '', // 发布数据间隔开始时间
  publishedIntervalEnd: '', // 发布数据间隔结束时间
  dealDayStart: '', // 成交数据每天开始时间
  dealDayEnd: '', // 成交数据每天结束时间
  dealIntervalStart: '', // 成交数据间隔开始时间
  dealIntervalEnd: '' // 成交数据间隔结束时间
})


const queryFormRefConfig = ref() // 搜索的表单
const exportLoadingConfig = ref(false)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ScheduledTaskApi.getScheduledTaskPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ScheduledTaskApi.deleteScheduledTask(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ScheduledTaskApi.exportScheduledTask(queryParams)
    download.excel(data, '定时任务数据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}



/** 查询定时任务配置详情 */
const getScheduledTaskConfiguration = async () => {
 
  try {
    const data = await ScheduledTaskConfigurationApi.getScheduledTaskConfiguration(1)
    console.log(data);
    if(data != null){
      scheduledTaskConfigurationVO.publishedDayStart = data.publishedDayStart;
      scheduledTaskConfigurationVO.publishedDayEnd = data.publishedDayEnd;
      scheduledTaskConfigurationVO.publishedIntervalStart = data.publishedIntervalStart
      scheduledTaskConfigurationVO.dealDayStart = data.dealDayStart;
      scheduledTaskConfigurationVO.dealDayEnd = data.dealDayEnd;
      scheduledTaskConfigurationVO.dealIntervalStart = data.dealIntervalStart;
    }
    
  } finally {
  }
}

/** 修改定时任务配置 */
const updateScheduledTaskConfiguration = async () => {
  const data = scheduledTaskConfigurationVO as unknown as ScheduledTaskConfigurationVO
  //判断是否为空
  if(data.publishedDayStart == '' || data.publishedDayEnd == '' || data.publishedIntervalStart == '' || data.dealDayStart == '' || data.dealDayEnd == '' || data.dealIntervalStart == ''){
    message.warning('请填写完整的配置信息')
    return
  }
 try {
   await ScheduledTaskConfigurationApi.updateScheduledTaskConfiguration(data);
   message.success(t('生效成功'))
 } finally {
 }
}

// 验证输入是否为数字-数字类型，并且第一个数字小于第二个数字
const validateInterval = (value: string, field: string) => {
  const regex = /^\d+-\d+$/;
  if (!regex.test(value)) {
    message.warning('输入格式必须为 数字-数字：10-20');
    // 清空不符合格式的输入
    scheduledTaskConfigurationVO[field] = ''; 
    return;
  }
  const [start, end] = value.split('-').map(Number);
  if (start >= end) {
    message.warning('第一个数字必须小于第二个数字');
    // 清空不符合要求的输入
    scheduledTaskConfigurationVO[field] = ''; 
  }
};
/** 初始化 **/
onMounted(() => {
  getList()
  //定时任务配置
  getScheduledTaskConfiguration()
})


</script>